package com.yisu.expressway.customService;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Created by Administrator on 2017/1/1.
 */

public class VoiceRecognizer {
    // no voice is recorded
    public static final int ERROR_NO_VOICE = 10118;

    interface VoiceRecognizeListener {
        void onSuccess(String result);
        void onError(String errMsg);
    }

    private boolean mInitialized = false;
    private StringBuffer mResultBuffer = new StringBuffer();
    // 语音听写对象
    private SpeechRecognizer mSpeechRecognizer;
    private static VoiceRecognizer mInstance;
    private VoiceRecognizeListener mVoiceRecognizeResultListener;

    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private VoiceRecognizer() {

    }

    public static VoiceRecognizer getInstance() {
        if (mInstance == null) {
            mInstance = new VoiceRecognizer();
        }
        return mInstance;
    }

    public void init(Context ctx) {
        if (!mInitialized) {
            mSpeechRecognizer = SpeechRecognizer.createRecognizer(ctx, mInitListener);
        }
    }

    public void startListening(VoiceRecognizeListener listener) {
        if (!mInitialized) {
            return;
        }

        // clear the buffer
        if (mResultBuffer.length() > 0) {
            mResultBuffer.delete(0, mResultBuffer.length());
        }

        mVoiceRecognizeResultListener = listener;
        // 设置参数
        setParam();

        int ret = mSpeechRecognizer.startListening(mRecognizerListener);
        if (ret != ErrorCode.SUCCESS) {
            if (mVoiceRecognizeResultListener != null) {
                listener.onError("error code = " + ret);
            }
        }
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {

            if (code != ErrorCode.SUCCESS) {
                mInitialized = false;
            } else {
                mInitialized = true;
            }
        }
    };

    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
        }

        @Override
        public void onError(SpeechError error) {
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
            if (error.getErrorCode() == ERROR_NO_VOICE) {
                if (mVoiceRecognizeResultListener != null) {
                    mVoiceRecognizeResultListener.onError("您没有说话");
                }
            }
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            if (results == null)
                return;

            if (isLast) {
                if (mVoiceRecognizeResultListener != null) {
                    mVoiceRecognizeResultListener.onSuccess(mResultBuffer.toString());
                }
            } else {
                String text =parseResult(results.getResultString());
                mResultBuffer.append(text);
            }
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        }
    };

    private void setParam() {
        // 清空参数
        mSpeechRecognizer.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mSpeechRecognizer.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mSpeechRecognizer.setParameter(SpeechConstant.RESULT_TYPE, "json");

        String lag = "mandarin";
        mSpeechRecognizer.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mSpeechRecognizer.setParameter(SpeechConstant.ACCENT, lag);

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mSpeechRecognizer.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mSpeechRecognizer.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mSpeechRecognizer.setParameter(SpeechConstant.ASR_PTT, "1");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mSpeechRecognizer.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mSpeechRecognizer.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
    }

    private static String parseResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }
}
